package com.java.base.exercise.current;

/**
 * @Author RenPu
 * @Date 2022/2/15 17:47
 * @Version 1.0
 * @Description: 自定义AQS，自定义实现独享锁和共享锁
 **/
public class Renpu_lock2 extends AQSdemo{

    AQSdemo aqSdemo =new AQSdemo();

        //尝试获取锁
        @Override
        public boolean tryAcquire() {
            //使用CAS获取锁，当旧值等于内存的值，就可以将内存值更改为期望值
            return aqSdemo.owen.compareAndSet(null,Thread.currentThread());
        }


        //尝试释放锁
        @Override
        public boolean tryRelease() {

            //使用CAS获取锁，当旧值等于内存的值，就可以将内存值更改为期望值
            return aqSdemo.owen.compareAndSet(Thread.currentThread(),null);
        }


    public void lock(){
        aqSdemo.acquire();
    }

    public void  unlock(){
      aqSdemo.release();
    }

    int count=0;
    public void add(){
        this.lock();
        try{
            count++;
        }finally {
            this.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Renpu_lock2 renpu_lock2 = new Renpu_lock2();

        for (int i = 0; i < 4; i++) {
            new Thread(()->{
                for (int j = 0; j <10000 ; j++) {
                    renpu_lock2.add();
                }
            }).start();

        }

        Thread.sleep(2000L);
        System.out.println(renpu_lock2.count);
    }


}
